/*
 * Copyright 2018 peipeihh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * limitations under the License.
 */
package com.pphh.demo;

import com.pphh.common.CookieUtils;
import com.pphh.common.DemoProperties;
import com.pphh.common.UserInfo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by huangyinhuang on 3/15/2018.
 */
@SpringBootApplication
@RestController
public class UserApp {

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }

    /**
     * 用户登录
     *
     * @param userInfo 用户名和密码
     * @param response 请求响应
     * @return
     */
    @PostMapping(value = "/api/login")
    public ResponseEntity<String> login(@RequestBody UserInfo userInfo,
                                HttpServletResponse response) {
        // 校验用户名和密码
        if (userInfo.getUserName().equals("test") && userInfo.getUserPwd().equals("test")) {
            // 若用户名和密码正确，则提示用户登录成功，并将用户信息存储在浏览器cookie中
            CookieUtils.addCookie(response, DemoProperties.cookieUserName, userInfo.getUserName());
            CookieUtils.addCookie(response, DemoProperties.cookieUserRole, userInfo.getUserRole());
            return new ResponseEntity<String>("succeeded to login. please view login user info in browser cookies.", HttpStatus.OK);
        } else {
            return new ResponseEntity<String>("failed to login. please input user name and password.", HttpStatus.UNAUTHORIZED);
        }

    }

    /**
     * 用户登录注销
     *
     * @param request  请求访问
     * @param response 请求响应
     * @return
     */
    @PostMapping(value = "/api/logout")
    public String login(HttpServletRequest request,
                        HttpServletResponse response) {
        CookieUtils.removeCookie(request, response, DemoProperties.cookieUserName);
        CookieUtils.removeCookie(request, response, DemoProperties.cookieUserRole);
        return "succeeded to logout.";
    }

    /**
     * 演示JSONP的跨域请求
     *
     * @param callback JS回调函数，用于输入参数后返回
     * @param userName 用户名
     * @return 返回一段JS可执行脚本
     */
    @GetMapping("/api/demo/jsonp")
    public String demoJsonp(@RequestParam(value = "callback", required = false) String callback,
                            @RequestParam(value = "user", required = true) String userName) {

        String message = String.format("Hello, %s. This is message from http://localhost:9001.", userName);
        if (callback == null) {
            // if there is no callback function, use alert function instead
            return "alert(\"" + message + "\");";
        } else {
            return callback + "(\"" + message + "\");";
        }

    }

    /**
     * 一个简单的API接口
     *
     * @return 返回欢迎信息
     */
    @GetMapping("/api/demo/hello")
    public String demoHello() {

        return "hello,world. This is message from http://localhost:9001.";

    }

    /**
     * 一个简单的API接口（允许跨域访问）
     *
     * @return 返回欢迎信息
     */
    @RequestMapping(value = "/api/demo/cors", method = {RequestMethod.GET, RequestMethod.POST})
    public String demoCors(HttpServletResponse response) {

        /**
         * 各个参数说明：
         * Access-Control-Allow-Origin 允许的跨域访问源
         * Access-Control-Allow-Method 允许的跨域访问方法
         * Access-Control-Max-Age 一次跨域预检请求有效时长
         * Access-Control-Allow-Headers
         */

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:9002");
        response.setHeader("Access-Control-Allow-Method", "GET, POST");
        response.setHeader("Access-Control-Max-Age", "86400");
        return "hello,world. This is message from http://localhost:9001.";

    }

}
